/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.anorien.dmo;

import eu.anorien.dmo.gui.MainFrame;
import eu.anorien.dmo.gui.optimization.Optimization;
import eu.anorien.dmo.gui.optimization.ServerPool;
import eu.anorien.dmo.proxy.LinuxProxy;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.log4j.BasicConfigurator;

/**
 *
 * @author David Miguel Antunes <davidmiguel [ at ] antunes.net>
 */
public class DistributedMatlabOptimization {

    private ArrayList<Server> servers = new ArrayList<Server>();
    private ArrayList<Function> functions = new ArrayList<Function>();
    private ArrayList<Optimization> optimizations = new ArrayList<Optimization>();
    private MainFrame mainFrame;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException, IOException {
        BasicConfigurator.configure();
        if (args.length == 0) {
            System.err.println("Requires 1 arg: 'interface' or 'linuxproxy'.");
            System.out.println("ASSUMING INTERFACE!");
            args = new String[]{"interface"};
        }

        String[] args2 = new String[args.length - 1];
        for (int i = 0; i < args2.length; i++) {
            args2[i] = args[i + 1];
        }

        if (args[0].equals("interface")) {
            new DistributedMatlabOptimization().doMain(args2);
        } else if (args[0].equals("linuxproxy")) {
            LinuxProxy.main(args2);
        } else {
            System.err.println("Requires 1 arg: 'interface' or 'linuxproxy'.");
            return;
        }
    }

    public void doMain(String[] args) throws FileNotFoundException, IOException {
        installFiles();
        ServerPool.init(servers);
        mainFrame = new MainFrame(this, servers, functions, optimizations);
        mainFrame.setVisible(true);
    }

    private void installFiles() throws FileNotFoundException, IOException {
        String[] files = new String[]{
            //"linux_compress_folder.sh",
        };
        for (int i = 0; i < files.length; i++) {
            String file = files[i];
            FileOutputStream fos = new FileOutputStream(file);
            InputStream is = getClass().getClassLoader().getResourceAsStream(file);
            while (is.available() > 0) {
                fos.write(is.read());
            }
            is.close();
            fos.close();
            new File(file).setExecutable(true);
        }
    }
    
    public void startOptimization(Optimization opt) {
        mainFrame.getOptimizationsPanel().newOptimization(opt);
    }
}
